<?php
/**
 * Fichier : index.php
 * Partie PHP : submit des scorings
**/

session_start();

define('MAX_HIGH_SCORE',400000);

/**
 * Connexion à PDO
**/
function pdoConnect( &$pdo )
{
	$_mysql_host	= 'localhost';
	$_mysql_db		= 'jam-rgb';
	$_mysql_user	= 'root';
	$_mysql_pass	= '';
	
	// Singleton function like
	if(!is_resource( $pdo ))
	{
		try
		{
			$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
			$pdo = new PDO( 'mysql:host='.$_mysql_host.';dbname='.$_mysql_db, $_mysql_user, $_mysql_pass, $pdo_options );
		}
		catch(Exception $e)
		{
			die('Erreur : ' . $e->getMessage());
		}
	}
}

/**
 * Récupération des scores
**/
function getScores( $table_score = 'rgb_scores' )
{
	global $pdo;
	
	$output = array();
	
	if( $table_score == 'rgb_scores_hackers' )	$limit = 0;
	else										$limit = 5;
	
	$q = $pdo->prepare('SELECT * FROM '.addslashes($table_score).' ORDER BY score DESC' . (($limit > 0) ? ' LIMIT '.$limit : ''));
	$q->execute();
	while($r = $q->fetch(PDO::FETCH_OBJ))
	{
		$output[] = $r;
	}
	$q->closeCursor();
	
	return $output;
}

/**
 * Envoi d'un score ?
**/
function submitScore( $infos )
{
	// Hacking détecté ?
	if( $infos['score'] > MAX_HIGH_SCORE )
	{
		$hacker = true;
		$table_score = 'rgb_scores_hackers';
	}
	else
	{
		$hacker = false;
		$table_score = 'rgb_scores';
	}
	
	/**
	 * Enregistrement
	**/
	
	global $pdo;
	
	$q = $pdo->prepare('INSERT INTO '.addslashes($table_score).' VALUES(
							:id,
							:pseudo,
							:score,
							NOW(),
							:ip,
							:platform
						)');
	$output = $q->execute( array(
						':id' => '',
						':pseudo' => $infos['pseudo'],
						':score' => $infos['score'],
						':ip' => $_SERVER['REMOTE_ADDR'],
						':platform' => $infos['platform']
						) );
						
	$q->closeCursor();
	
	return $output;
}

/**
 * Vérifie si $score est dans le top 5 des high scores
**/
function checkTop5( $score )
{
	global $pdo;
	
	$output = array();
	
	$q = $pdo->prepare('SELECT * FROM rgb_scores GROUP BY score ORDER BY score DESC LIMIT 5');
	$q->execute();
	$count = $q->rowCount();
	while($data = $q->fetch(PDO::FETCH_OBJ)) {
		$fifthScore = $data->score;
	}
	$q->closeCursor();
	
	// $fifthScore contient maintenant le plus petit score
	if( $count < 5 || $score > $fifthScore )
		return true;
	else
		return false;
}

/**
 * Détecte la plate-forme utilisée pour jouer
**/
function getPlatform()
{
	// PC/Mac ?
	if( (preg_match('#Chrome#', $_SERVER['HTTP_USER_AGENT']) || preg_match('#Firefox#', $_SERVER['HTTP_USER_AGENT'])) && !preg_match('#Mobile#i', $_SERVER['HTTP_USER_AGENT']) )
	{
		return '1'; // 1 = id PC dans la table de reférénce des plates-formes
	}
	else if( (preg_match('#Android#', $_SERVER['HTTP_USER_AGENT']) || preg_match('#PlayBook#', $_SERVER['HTTP_USER_AGENT']) || preg_match('#iPad#', $_SERVER['HTTP_USER_AGENT'])) && !preg_match('#Mobile#i', $_SERVER['HTTP_USER_AGENT']) )
	{
		return '2'; // 2 = id Tablette dans la table de reférénce des plates-formes
	}
	else if( preg_match('#iPhone#', $_SERVER['HTTP_USER_AGENT']) || (preg_match('#Safari Mobile#i', $_SERVER['HTTP_USER_AGENT']) && preg_match('#Android#', $_SERVER['HTTP_USER_AGENT'])) )
	{
		return '3'; // 3 = id Smartphones dans la table de reférénce des plates-formes
	}
	else
	{
		return '4'; // 4 = id unknown
	}
}

/*********************************************
 ************** DEBUT DU SCRIPT **************
*********************************************/

$pdo = null;
pdoConnect( $pdo );

/**
 * Requête AJAX demandant si l'on se trouve dans le top 5...
**/
if( isset($_POST['isAHighScore']) )
{
	if(checkTop5( $_POST['isAHighScore'] ))
		die('1'); // Succès
	else
		die('0'); // Echec
}

// -----
// Formulaire pour envoyer un scoring ?
// -----
if(isset( $_POST['score'] ))
{
	if( ctype_digit($_POST['score']) )
		$_SESSION['score'] = $_POST['score'];
}

// -----
// Soumission de scoring
// -----
if(isset( $_POST['submit_score'] ))
{
	if(!empty( $_POST['pseudo'] ))
	{
		$infos = array(
			'pseudo' => $_POST['pseudo'],
			'score' => $_SESSION['score'],
			'platform' => getPlatform()
		);
		
		if(submitScore( $infos ))
		{
			if( $infos['score'] > MAX_HIGH_SCORE )
				Header('Location:scoring.php?hackers-wall');
			else
				Header('Location:scoring.php');
		}
		else
		{
			Header('Location:scoring.php?err=500');
		}
	}
}

?><!DOCTYPE HTML>
<html>
	<head>
		<style type="text/css">
			body{
				background-color: #000;
				color: #FFF;
				font-family: Arial, "MS Trebuchet", sans-serif;
				text-align: center;
				margin: 0;
				padding: 0;
			}
			
			@font-face {
			    font-family: 'MolotRegular';
			    src: url('font/Molot-webfont.eot');
			    src: url('font/font/Molot-webfont.eot?#iefix') format('embedded-opentype'),
			         url('font/Molot-webfont.ttf') format('truetype'),
			         url('font/Molot-webfont.svg#MolotRegular') format('svg');
			    font-weight: normal;
			    font-style: normal;
			}
			
			a:link,
			a:visited {
				color: #000;
				text-decoration: underline;
			}
			a:hover,
			a:active,
			a:focus {
				text-decoration: none;
			}
			
			.container-scoring {
				background-color: #a80312;
				width: 1024px;
				height: 600px;
				position: absolute;
				top: 7px;
				left: 50%;
				margin: 0 0 0 -512px;
				box-shadow: 0 0 15px rgb(254,0,45);
				border-radius: 15px;
			}
			.container-scoring * {
				font-family: 'MolotRegular';
			}
				.container-scoring h2 {
					font-size: 38px;
				}
				.container-scoring .tbl {
					width: 98%;
					margin: 0 auto;
					border-collapse: collapse;
					border: 0 none;
				}
				.container-scoring .tbl th {
					background-color: #444;
					padding: 10px 6px;
					text-align: left;
					color: #000;
					font-size: 22px;
					font-weight: normal;
					text-shadow: 0 0 25px #fff;
					border: 4px solid #000;
				}
				.container-scoring .tbl th.platform { width: 48px; }
				.container-scoring .tbl th.pseudo { width: 350px; }
				.container-scoring .tbl th.score { width: 250px; }
				.container-scoring .tbl td {
					font-size: 28px;
					text-shadow: 1px 1px 7px #c0c0c0;
				}
				.container-scoring input.txt {
					width: 350px;
					padding: 10px;
					font-family: 'Lucida Console', 'Lucida Sans', 'Trebuchet MS', sans-serif;
					font-size: 18px;
					font-weight: bold;
					text-align: center;
					border: 1px solid #c0c0c0;
					border-radius: 10px;
					box-shadow: 0 0 15px #c0c0c0;
				}
				.container-scoring input.btn {
					background-image: linear-gradient(bottom, rgb(171,36,36) 21%, rgb(255,110,122) 54%, rgb(250,75,77) 77%);
					background-image: -o-linear-gradient(bottom, rgb(171,36,36) 21%, rgb(255,110,122) 54%, rgb(250,75,77) 77%);
					background-image: -moz-linear-gradient(bottom, rgb(171,36,36) 21%, rgb(255,110,122) 54%, rgb(250,75,77) 77%);
					background-image: -webkit-linear-gradient(bottom, rgb(171,36,36) 21%, rgb(255,110,122) 54%, rgb(250,75,77) 77%);
					background-image: -ms-linear-gradient(bottom, rgb(171,36,36) 21%, rgb(255,110,122) 54%, rgb(250,75,77) 77%);

					background-image: -webkit-gradient(
						linear,
						left bottom,
						left top,
						color-stop(0.21, rgb(171,36,36)),
						color-stop(0.54, rgb(255,110,122)),
						color-stop(0.77, rgb(250,75,77))
					);
					color: #fff;
					cursor: pointer;
					margin-top: 25px;
					padding: 10px;
					font-size: 18px;
					border: 0 none;
					border-radius: 10px;
					box-shadow: 0 0 15px #f00;
				}
				.hc-mode {
					background-color: #72c73e;
					box-shadow: 0 0 15px #0f0;
					height: auto !important;
				}
				.hc-back {
					background: #000 url('../assets/img/hc-back.jpg') top left repeat-x;
				}
		</style>
		<script type="text/javascript" src="Xhr.js"></script>
		<script>
			function checkForm() {
				var pseudo = document.getElementById('pseudo');
				if( pseudo.value == '' ) {
					alert('You must enter a nick !');
					return false;
				}
				
				return true;
			}
		</script>
	</head>
	<body<?php echo isset( $_GET['hackers-wall'] ) ? ' class="hc-back"' : ''; ?>>
		
		<?php // Formulaire de soumission
		if(isset( $_POST['score'] )) : ?>
			<div class="container-scoring">
				
				<h2>Congratulations!</h2>
				<h2>Your score <span style="color: #a3fe6b;"><?php echo htmlspecialchars($_SESSION['score']); ?></span> is in the top 5</h2>
				
				<br />
				<br />
				<form method="post" id="form-submit" action="scoring.php" onsubmit="return checkForm();">
					<h3>Type your nick</h3>
					<input type="text" name="pseudo" id="pseudo" class="txt" /><br />
					<input type="submit" name="submit_score" value="Submit to server" class="btn" />
				</form>
				
			</div>
		<?php // Page des scorings standard
		else : ?>
			
			<div class="container-scoring<?php echo isset( $_GET['hackers-wall'] ) ? ' hc-mode' : ''; ?>">
				
				<?php // Omg! Hacker wall!
				if(isset( $_GET['hackers-wall'] )) : ?>
					<h2>Hall of SHAME - RGB</h2>
					<p>
						Shame on you ! You attempted to cheat to our wonderful game RGB by submitting a fake score.<br />
						You, and your fellow hackers, deserve to figure on this hall of shame for cheating offense.
					</p>
					<table border="0" cellpadding="0" cellspacing="0" class="tbl">
						<tr>
							<th class="platform">&nbsp;</th>
							<th class="pseudo">Pseudo</th>
							<th class="score">Score</th>
							<th class="submitted">Submitted</th>
						</tr>
						<?php
						$scores = getScores('rgb_scores_hackers');
						foreach( $scores as $score ) : ?>
						<tr>
							<td><img src="../assets/img/icons/<?php echo $score->platform_id; ?>.png" /></td>
							<td><?php echo htmlspecialchars(stripslashes($score->pseudo)); ?></td>
							<td><?php echo htmlspecialchars(stripslashes($score->score)); ?></td>
							<td><?php echo $score->date; ?></td>
						</tr>
						<?php endForeach; ?>
					</table>
					<br />
				<?php // Phiew! Normal wall
				else : ?>
					<h2>Hall of Fame - RGB</h2>
					
					<table border="0" cellpadding="0" cellspacing="0" class="tbl">
						<tr>
							<th class="platform">&nbsp;</th>
							<th class="pseudo">Pseudo</th>
							<th class="score">Score</th>
							<th class="submitted">Submitted</th>
						</tr>
						<?php
						$scores = getScores();
						foreach( $scores as $score ) : ?>
						<tr>
							<td><img src="../assets/img/icons/<?php echo $score->platform_id; ?>.png" /></td>
							<td><?php echo htmlspecialchars(stripslashes($score->pseudo)); ?></td>
							<td><?php echo htmlspecialchars(stripslashes($score->score)); ?></td>
							<td><?php echo $score->date; ?></td>
						</tr>
						<?php endForeach; ?>
					</table>
					<br />
				<?php endIf; ?>
				
				<p align="center">
					Share <?php echo isset( $_GET['hackers-wall'] ) ? 'this shame' : 'scores'; ?> :<br />
					<span style="font-family: Georgia, serif; font-size: 26px;">http://jmpp.fr/games/rgb-jam/src/scoring.php<?php echo isset( $_GET['hackers-wall'] ) ? '?hackers-wall' : ''; ?></span><br />
					<br />
					<br />
					<a href="index.html">Go back to Game</a>
				</p>
				
			</div>
		<?php endIf; ?>
		
		<script type="text/javascript">
		  var _gaq = _gaq || [];
		  _gaq.push(['_setAccount', 'UA-29118878-1']);
		  _gaq.push(['_trackPageview']);

		  (function() {
			var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
			ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
			var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
		  })();

		</script>
	</body>
</html>